package com.fire.article.controller;

import com.fire.article.entity.Articles;
import com.fire.article.service.ArticleService;

import com.fire.common.controller.BaseController;
import com.fire.common.core.page.TableDataInfo;
import com.fire.common.domain.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


import java.io.File;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/article")
public class ArticleController extends BaseController {


    @Autowired
    private ArticleService articleService;

    //分页查询商品的url接口/product/product-page-list
    @RequestMapping("/getArticleList")
    public TableDataInfo getArticleList(@RequestBody Articles articles){
        startPage();
        List<Articles> articlesList = articleService.getArticlesList(articles);
        return getDataTable(articlesList);
    }

    //添加观看量
    @PostMapping("/addViewerNumber")
    public Result addViewerNumber(@RequestParam("articleId") Integer articleId){
        Result result = articleService.addNumber(articleId);
        return result;
    }

    //更新文章
    @PostMapping("/updateArticle")
    public Result updateArticle(@RequestBody Articles articles){
        Result result = articleService.updateArticles(articles);
        return result;
    }

    //删除文章
    @PostMapping("/deleteArticle")
    public Result deleteArticle(@RequestParam("articleId") Integer articleId){
        Result result = articleService.deleteArticles(articleId);
        return result;
    }

    //添加文章
    @PostMapping("/addArticle")
    public Result addArticle(@RequestBody Articles articles){
        //执行业务
        Result result = articleService.insertArticles(articles);

        //响应
        return result;
    }


    //上传路径
    private String uploadPath = "classpath:static/img/upload";

    //上传图片
    @CrossOrigin
    @PostMapping("/img-upload")
    public Result uploadImg(MultipartFile file){

        try {
            //拿到图片上传到的目录(类路径classes下的static/img/upload)的File对象
            File uploadDirFile = ResourceUtils.getFile(uploadPath);
            //拿到图片上传到的目录的磁盘路径
            String uploadDirPath = uploadDirFile.getAbsolutePath();
            //拿到图片保存到的磁盘路径
            String fileUploadPath = uploadDirPath + "\\" + file.getOriginalFilename();
            //保存图片
            file.transferTo(new File(fileUploadPath));
            //成功响应
            return Result.ok("图片上传成功！");
        } catch (IOException e) {
            //失败响应
            return Result.err(Result.CODE_ERR_BUSINESS, "图片上传失败！");
        }
    }
}
